import Header from './Header';
import Search from './Search'
import Movie from './Movie'
import './App.css';
import React, { useReducer, useEffect } from 'react';
// 电影api
const MOVIE_API_URL = "https://www.omdbapi.com/?s=man&apikey=4a3b711b"; 

const initialState = {
  loading: true,
  movies: [],
  errorMessage: null
}
// 三个状态 SEARCH_MOVIES_REQUEST/SEARCH_MOVIES_SUCCESS/SEARCH_MOVIES_FAILURE
const reducer = (state, action) => {
  switch(action.type) {
    case 'SEARCH_MOVIES_REQUEST':
      return {
        ...state,
        loading: true,
        errorMessage: null
      }
      case 'SEARCH_MOVIES_SUCCESS':
        return {
          ...state,
          loading: false,
          movies: action.playload
        }
      case 'SEARCH_MOVIES_FAILURE':
        return {
          ...state,
          loading: false,
          errorMessage: action.error
        }
      default:
    return state;
  }
}
// 无关键字或错误数据 {"Response":"False","Error":"Incorrect IMDb ID."}
const App = () => {
  // 设置state状态
  // const [loading, setLoading] = useState(true)
  // const [movies, setMovies] = useState([])
  // const [errorMessage, setErrorMessage] = useState(null)
  // useEffect(() => {
  //   fetch(MOVIE_API_URL)
  //   .then(response => response.json())
  //   .then(jsonResPonse => {
  //     setLoading(false);
  //     setMovies(jsonResPonse.Search);
  //   })
  // }, [])
  // const search = searchValue => {
  //   setLoading(true);
  //   setErrorMessage(null);
  //   fetch(`https://www.omdbapi.com/?s=${searchValue}&apikey=4a3b711b`)
  //   .then(response => response.json())
  //   .then(jsonResponse => {
  //     if (jsonResponse.Response === 'True') {
  //       setLoading(false);
  //       setMovies(jsonResponse.Search);
  //     } else {
  //       setLoading(false);
  //       setErrorMessage(jsonResponse.Error);
  //     }
  //   })
  // }
  // 用useReducer替换useState
  const [state, dispatch] = useReducer(reducer, initialState);
    useEffect(() => {
      fetch(MOVIE_API_URL)
      .then(response => response.json())
      .then(jsonResPonse => {
        dispatch({
          type: 'SEARCH_MOVIES_SUCCESS',
          playload: jsonResPonse.Search 
        })
      })
    }, [])
   const search = searchValue => {
    dispatch({
      type: "SEARCH_MOVIES_REQUEST"
    });
    // setLoading(true);
    // setErrorMessage(null);
    fetch(`https://www.omdbapi.com/?s=${searchValue}&apikey=4a3b711b`)
    .then(response => response.json())
    .then(jsonResponse => {
      if (jsonResponse.Response === 'True') {
        // setLoading(false);
        // setMovies(jsonResponse.Search);
        dispatch({
          type: 'SEARCH_MOVIES_SUCCESS',
          playload: jsonResponse.Search 
        });
      } else {
        // setLoading(false);
        // setErrorMessage(jsonResponse.Error);
        dispatch({
          type: 'SEARCH_MOVIES_FAILURE',
          errorMessage: jsonResponse.Error 
        });
      }
    })
  }
  const { movies, loading, errorMessage } = state;
  return (
    <div className="App">
      <Header text="HOOKED"/>
      <Search search={search}/>
      <p className="App-intro">Sharing a few of our favourite movies</p>
      <div className="movies">
        {
          loading && !errorMessage ? (<span>...loading</span>) : errorMessage ? (<div className="errorMessage">{errorMessage}</div>)
          : (movies.map((movie, index) => (
            <Movie key={`${index}-${movie.title}`} movie={movie}/>
          )))
        }
      </div>
    </div>
  );
}

export default App;
